package com.txts.road.admin.beidou.api.v1.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@Tag(name = "天气接口")
public class WeatherController {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private ObjectMapper objectMapper;

    private static final String AMAP_KEY = "a6e9b76b00067834222f5342d6cd0406";

    @PostMapping("/weatherRaw")
    public ResponseEntity<String> postWeatherBySection(@RequestBody Map<String, String> body) {
        String sectionName = body.get("sectionName");
        if (sectionName == null || sectionName.isEmpty()) {
            return ResponseEntity
                    .status(HttpStatus.BAD_REQUEST)
                    .body("{\"error\":\"缺少字段 sectionName\"}");
        }
        // 其余逻辑与 GET 一致，直接复用：
        return getWeatherBySection(sectionName);
    }

    public ResponseEntity<String> getWeatherBySection(
            @RequestParam("sectionName") String sectionName) {

        // 1. 从数据库取出 saishiweizhi
        String sql = "SELECT saishiweizhi FROM race_section WHERE section_name = ?";
        String address;
        try {
            address = jdbcTemplate.queryForObject(
                    sql,
                    new Object[]{sectionName},
                    String.class
            );
        } catch (EmptyResultDataAccessException ex) {
            return ResponseEntity
                    .status(HttpStatus.NOT_FOUND)
                    .body("{\"error\":\"未找到赛段位置\"}");
        }
        address = address.split(",")[1] + "," + address.split(",")[0];
        System.out.println(address);
        try {
            // 2. 地理编码
            JsonNode geoNode = callAmapRegeo(address);
            if (geoNode == null) {
                throw new RuntimeException("地理编码失败");
            }
            System.out.println(geoNode);
            String location = geoNode.path("location").path("streetNumber").path("location").asText();
            String adcode = geoNode.path("addressComponent").path("adcode").asText();
            System.out.println("------------" + location);
            System.out.println(adcode);
            // 3. 天气查询
            JsonNode liveNode = callAmapWeather(adcode);
            if (liveNode == null) {
                throw new RuntimeException("天气查询失败");
            }

            // 4. 组装并返回
            JsonNode result = objectMapper.createObjectNode()
                    .put("sectionName", sectionName)
                    .put("address", address)
                    .put("location", location)
                    .put("adcode", adcode)
                    .set("weather", liveNode);

            return ResponseEntity.ok()
                    .header("Content-Type", "application/json; charset=UTF-8")
                    .body(objectMapper.writeValueAsString(result));

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    private JsonNode callAmapRegeo(String location) throws Exception {
        String url = "https://restapi.amap.com/v3/geocode/regeo"
                + "?key=" + URLEncoder.encode(AMAP_KEY, "UTF-8")
                + "&location=" + URLEncoder.encode(location, "UTF-8")
                + "&extensions=base"      // 只返回基础地址信息【:contentReference[oaicite:2]{index=2}】
                + "&output=JSON";

        // 发起请求
        String resp = httpGet(url);
        System.out.println("Regeo resp: " + resp);

        // 解析
        JsonNode root = objectMapper.readTree(resp);
        if (!"1".equals(root.path("status").asText()) ||
                !"10000".equals(root.path("infocode").asText())) {
            throw new RuntimeException("逆地理编码失败: info="
                    + root.path("info").asText());
        }

        // 拿到完整的 regeocode 节点，后续可用 addressComponent.adcode
        return root.path("regeocode");
    }


    private JsonNode callAmapWeather(String adcode) throws Exception {
        String url = "https://restapi.amap.com/v3/weather/weatherInfo"
                + "?key=" + URLEncoder.encode(AMAP_KEY, "UTF-8")
                + "&city=" + URLEncoder.encode(adcode, "UTF-8")
                + "&extensions=base";
        String resp = httpGet(url);
        JsonNode root = objectMapper.readTree(resp);
        if ("1".equals(root.path("status").asText())) {
            return root.path("lives").get(0);
        }
        return null;
    }

    private String httpGet(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream(), "UTF-8"))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        }
    }

    /**
     * —— 新增代码开始 ——
     * 放宽 Tomcat 对 Query 字符的校验，允许中文直接出现在 URL 中
     */
    @Bean
    public WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatCustomizer() {
        return factory -> factory.addConnectorCustomizers(connector -> {
            // 允许未编码的中文（Unicode 范围）在 query 中出现 :contentReference[oaicite:0]{index=0}
            connector.setProperty("relaxedQueryChars", "\u4e00-\u9fa5");
            // 确保使用 UTF-8 解码请求行 :contentReference[oaicite:1]{index=1}
            connector.setProperty("URIEncoding", "UTF-8");
            connector.setProperty("useBodyEncodingForURI", "true");
        });
    }
    /** —— 新增代码结束 —— **/
}
